#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;
int flag = 0;
int gnum = 0;


void* func1(void * arg){
    //flag == 0 时运行
    for(int i = 0;i < 200000; ++i){
        pthread_mutex_lock(&mutex);
        
        while(flag == 1){
            pthread_cond_wait(&cond,&mutex);
        }
        ++gnum;      
        pthread_cond_signal(&cond) ;       
        flag = 1;
        if(i >= 199990){
            printf("func1 : num : %d\n",gnum);
        }
        pthread_mutex_unlock(&mutex);

    }
}

void* func2(void * arg){
    //flag == 1 时运行
    for(int i = 0;i < 200000; ++i){
        pthread_mutex_lock(&mutex);
        
        while(flag == 0){
            pthread_cond_wait(&cond,&mutex);
        }
        ++gnum;      
        pthread_cond_signal(&cond) ;       
        flag = 0;
        if(i >= 199990){
            printf("func2 : num : %d\n",gnum);
        }
        pthread_mutex_unlock(&mutex);

    }
}


int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);

    pthread_t pthid1;
    pthread_t pthid2;

    pthread_create(&pthid1,NULL,func1,NULL);
    pthread_create(&pthid2,NULL,func2,NULL);
    pthread_join(pthid1,NULL);
    pthread_join(pthid2,NULL);
    return 0;
}

